package com.zdy.im.user.facade;

import com.sixeco.framework.common.data.BasePage;
import com.sixeco.framework.common.enums.TbStatusEnum;
import com.sixeco.framework.http.data.vo.ResponseResultList;
import com.sixeco.framework.http.exception.SystemRuntimeException;
import com.zdy.im.enums.ImResultCodeEnum;
import com.zdy.im.user.dto.request.ImRoomUserShipRequestDto;
import com.zdy.im.user.dto.response.ImRoomInfoResponseDto;
import com.zdy.im.user.dto.response.ImRoomUserShipResponseDto;
import com.zdy.im.user.dto.response.UserInfoResponseDto;
import com.zdy.im.user.service.ImRoomInfoService;
import com.zdy.im.user.service.ImRoomUserShipService;
import com.zdy.im.user.service.UserInfoService;
import com.zdy.im.user.vo.request.*;
import com.zdy.im.user.vo.response.ImRoomUserShipShowResponseVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Title: ImRoomUserShipFacade.java
 * @Author 作者 : zdy
 * @CreateDate 创建时间: 2021-02-30
 * @version V1.0  
 *  <pre>
 * 修改记录
 *    修改后版本:     修改人：  修改日期:     修改内容:
 * </pre>
 * @Description: TODO(说明) 对象缓存统一模板实现类;  
 */
 
@Component
public class ImRoomUserShipFacade {

	@Autowired
	private ImRoomUserShipService imRoomUserShipService;
	@Autowired
	private ImRoomInfoService imRoomInfoService;
	@Autowired
	private UserInfoService userInfoService;


	public ResponseResultList list(RoomUserQueryRequestVo roomUserQueryRequestVo){
		ImRoomUserShipRequestDto imRoomUserShipRequestDto = ImRoomUserShipRequestDto.build( ).clone(roomUserQueryRequestVo);

		BasePage page =  BasePage.build().toPageSize(roomUserQueryRequestVo.getPageSize()).toPageNo(roomUserQueryRequestVo.getPageNo());
		page.toParamObject(imRoomUserShipRequestDto );
		ResponseResultList<ImRoomUserShipResponseDto> resultList = imRoomUserShipService.getImRoomUserShipByNextPage(page);

		if(null == resultList || resultList.getList().isEmpty() ){
			return ResponseResultList.build();
		}

		Set<Long> userIds = new HashSet<>();
		resultList.getList().forEach(e ->{
			userIds.add(e.getUserId());
		});
		//查询用户信息，头像信息
		Map<Long, UserInfoResponseDto> userMap = userInfoService.getUserInfoByIds( userIds);

		List<ImRoomUserShipShowResponseVo> listVo = new ArrayList<>();
		resultList.getList().forEach(e -> {
			ImRoomUserShipShowResponseVo vo = ImRoomUserShipShowResponseVo.build().clone(e);
			if(!CollectionUtils.isEmpty(userMap) && userMap.get(e.getUserId()) != null){
				vo.setUserHeadImg(userMap.get(e.getUserId()).getHeadImg());
				vo.setUserName(userMap.get(e.getUserId()).getUserName());//用户昵称名字
			}

			listVo.add(vo);
		});

		ResponseResultList list =  ResponseResultList.build().toList(listVo)
				.toIsNextPage(resultList.getIsNextPage())
				.toPageIndex(resultList.getPageIndex())
				.toTotal(resultList.getTotal());
		return list;
	}

	/**
	 * 删除好友
	 * @param delFriendVo
	 * @return
	 */
	public boolean delRoomFriend( RoomUserRequestVo delFriendVo){
		ImRoomUserShipResponseDto imRoomUserShipDto = imRoomUserShipService.selectRoomFriend(delFriendVo.getUserId(), delFriendVo.getRoomId());
		if(imRoomUserShipDto == null ){
			throw new SystemRuntimeException(ImResultCodeEnum.IM_USER_NOT_EXIST);
		}
		/*if(imRoomUserShipDto != null && imRoomUserShipDto.getUserRole() == 99 ){
			throw new SystemRuntimeException(ImResultCodeEnum.IM_USER_ROOM_NOT_DEL);
		}
		List<Long> ids = new ArrayList<>();
		ids.add(imRoomUserShipDto.getId());*/
		imRoomUserShipDto.setStatus(TbStatusEnum.DISABLE.index());
		return imRoomUserShipService.updateImRoomUserShip(ImRoomUserShipRequestDto.build().clone(imRoomUserShipDto));
	}

	/**
	 * 修改群好友昵称/设置管理员
	 * @param roomFriendVo
	 * @return
	 */
	public boolean upnickName( RoomUserNameRequestVo roomFriendVo){
		if(roomFriendVo.getUserRole() == 99 ){
			throw new SystemRuntimeException(ImResultCodeEnum.IM_USER_ROOM_NOT_ROLE);
		}
		ImRoomUserShipResponseDto imRoomUserShipDto = imRoomUserShipService.selectRoomFriend(roomFriendVo.getUserId(), roomFriendVo.getRoomId());
		if(imRoomUserShipDto == null ){
			throw new SystemRuntimeException(ImResultCodeEnum.IM_USER_NOT_EXIST);
		}
		if(StringUtils.isNotBlank(roomFriendVo.getNickName())){
			imRoomUserShipDto.setNickName(roomFriendVo.getNickName());//修改群好友昵称
		}
		if(roomFriendVo.getUserRole() > 0){
			imRoomUserShipDto.setUserRole(roomFriendVo.getUserRole());//类型 0 用户，1.管理员，99.群主
		}else if(roomFriendVo.getUserRole() == -1){
			imRoomUserShipDto.setUserRole(0);//类型 0 用户，1.管理员，99.群主
		}
		return imRoomUserShipService.updateImRoomUserShip(ImRoomUserShipRequestDto.build().clone(imRoomUserShipDto));
	}


	/**
	 * 修改群好友设置/群员禁言
	 * @param roomFriendVo
	 * @return
	 */
	public boolean upnickSet( RoomUserNameRequestVo roomFriendVo){
		ImRoomUserShipResponseDto imRoomUserShipDto = imRoomUserShipService.selectRoomFriend(roomFriendVo.getUserId(), roomFriendVo.getRoomId());
		if(imRoomUserShipDto == null ){
			throw new SystemRuntimeException(ImResultCodeEnum.IM_USER_NOT_EXIST);
		}
		if(roomFriendVo.getRoomSet() > 0){
			imRoomUserShipDto.setRoomSet(roomFriendVo.getRoomSet());//修改群好友消息设置
		}else if(roomFriendVo.getRoomSet() == -1){
			imRoomUserShipDto.setRoomSet(0);//修改群好友消息设置
		}

		if(roomFriendVo.getForbidSpeech() > 0){
			imRoomUserShipDto.setForbidSpeech(roomFriendVo.getForbidSpeech());//群员禁言(1：已禁言,-1：未禁言)
		}else if(roomFriendVo.getForbidSpeech() == -1){
			imRoomUserShipDto.setForbidSpeech(0);//群员禁言(1-已禁言,0-未禁言)
		}
		return imRoomUserShipService.updateImRoomUserShip(ImRoomUserShipRequestDto.build().clone(imRoomUserShipDto));
	}

	public boolean add(RoomAddFirendRequestVo roomInfoAddRequestVo){

		Set<Long> userIds = new HashSet<>();
		if(StringUtils.isNotBlank(roomInfoAddRequestVo.getUserIds())){
			List<String> ids =  Arrays.asList(roomInfoAddRequestVo.getUserIds().split(","));
			userIds.addAll(ids.stream().map(a->{return Long.valueOf(a);}).collect(Collectors.toSet()));
		}
		if(CollectionUtils.isEmpty(userIds)){
			throw new SystemRuntimeException(ImResultCodeEnum.IM_USER_ROOM_FIREND_NOT_EXIST);
		}
		//查询群是否存在
		ImRoomInfoResponseDto imRoomInfoResponseDto = imRoomInfoService.getImRoomInfoById(roomInfoAddRequestVo.getRoomId());
		if(imRoomInfoResponseDto == null){
			throw new SystemRuntimeException(ImResultCodeEnum.IM_USER_ROOM_NOT_EXIST);
		}

		Map<Long, UserInfoResponseDto> userMap = userInfoService.getUserInfoByIds( userIds);

		//添加群用户关系
		List<ImRoomUserShipRequestDto> roomUserList = new ArrayList<>();
		userIds.forEach(e->{
			ImRoomUserShipRequestDto imRoomUserShipRequestDto = ImRoomUserShipRequestDto.build()
					.toRoomId(imRoomInfoResponseDto.getId())//群id
					.toUserId(e)
					.toForbidSpeech(0)//全群禁言(1-已禁言,0-未禁言)
					.toRoomSet(TbStatusEnum.ENABLE.index())//群设置 0不接受消息 1接收消息
					.toStatus(TbStatusEnum.ENABLE.index());//删除状态(1-正常,0-已删除)
			imRoomUserShipRequestDto.toUserRole(0);//类型 0 用户，1.管理员，99.群主
			if(!CollectionUtils.isEmpty(userMap) && userMap.get(e) != null){
				imRoomUserShipRequestDto.toNickName(userMap.get(e).getUserName());//用户群昵称/备注昵称
			}
			roomUserList.add(imRoomUserShipRequestDto);
		});

		if(!CollectionUtils.isEmpty(roomUserList)){
			imRoomUserShipService.saveBatchImRoomUserShip(roomUserList,roomUserList.size());
		}
		return true;
	}

	public ResponseResultList selectForbidSpeechList(ForbidSpeechRequestVo forbidSpeechRequestVo){
		ImRoomUserShipRequestDto imRoomUserShipRequestDto = ImRoomUserShipRequestDto.build().clone(forbidSpeechRequestVo);
		imRoomUserShipRequestDto.setForbidSpeech(1);//群员禁言(1-已禁言,0-未禁言)
		List<ImRoomUserShipResponseDto> roomUsers = imRoomUserShipService.selectListByRoomId(imRoomUserShipRequestDto);
		if(null == roomUsers || roomUsers.isEmpty() ){
			return ResponseResultList.build();
		}
		Set<Long> userIds = new HashSet<>();
		roomUsers.forEach(e ->{
			userIds.add(e.getUserId());
		});

		//查询用户信息，头像信息
		Map<Long, UserInfoResponseDto> userMap = userInfoService.getUserInfoByIds( userIds);

		List<ImRoomUserShipShowResponseVo> listVo = new ArrayList<>();
		roomUsers.forEach(e -> {
			ImRoomUserShipShowResponseVo vo = ImRoomUserShipShowResponseVo.build().clone(e);
			if(!CollectionUtils.isEmpty(userMap) && userMap.get(e.getUserId()) != null){
				vo.setUserHeadImg(userMap.get(e.getUserId()).getHeadImg());
				vo.setUserName(userMap.get(e.getUserId()).getUserName());//用户昵称名字
			}

			listVo.add(vo);
		});
		return ResponseResultList.build().toList(listVo).toTotal(listVo.size());
	}

	/**
	 * 批量删除群好友
	 * @param delFriendVo
	 * @return
	 */
	public boolean batchDelRoomFriend( RoomUserBatchRequestVo delFriendVo){
		Set<Long> userIds = new HashSet<>();
		if(StringUtils.isNotBlank(delFriendVo.getUserIds())){
			List<String> ids =  Arrays.asList(delFriendVo.getUserIds().split(","));
			userIds.addAll(ids.stream().map(a->{return Long.valueOf(a);}).collect(Collectors.toSet()));
		}
		if(CollectionUtils.isEmpty(userIds)){
			throw new SystemRuntimeException(ImResultCodeEnum.IM_USER_ROOM_FIREND_NOT_EXIST);
		}

		List<ImRoomUserShipResponseDto> imRoomUserShipDtos = imRoomUserShipService.selectRoomFriend(userIds, delFriendVo.getRoomId());
		if(CollectionUtils.isEmpty(imRoomUserShipDtos)){
			throw new SystemRuntimeException(ImResultCodeEnum.IM_USER_NOT_EXIST);
		}

		List<ImRoomUserShipRequestDto> listVo = new ArrayList<>();
		imRoomUserShipDtos.forEach(e -> {
			e.setStatus(TbStatusEnum.DISABLE.index());
			listVo.add(ImRoomUserShipRequestDto.build().clone(e));
		});

		return imRoomUserShipService.updateBatchById(listVo,listVo.size());
	}
}
